package com.kexun.util;


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class DBUtil {

    private String driverClass;
    private String url;
    private String username;
    private String password;
    private Connection coon = null;
    private Statement stmt = null;
    private ResultSet rs = null;

    public Connection getConnection() {
         Connection coons = null;
        //1使用当前类加载器,以流的形式读取配置文件,和类一起加载(比jdbc01/jdbc02多了一步,更完善/更加全面/更好)
        try {
            InputStream is= DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
            //2.将输入流读取到配置文件信息保存到properties对象ps里
            Properties ps = new Properties();
            ps.load(is);
            driverClass = ps.getProperty("driverClass");
                    url = ps.getProperty("url");
            username = ps.getProperty("username");
            password = ps.getProperty("password");

//加载驱动
            Class.forName(driverClass);

//获取连接
           coons = DriverManager.getConnection(url,username,password);




        } catch (IOException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return coons;
    }



    //  两个需求   :1 查询   2 增删改


    //定义一个查询方法query
    public ResultSet query(String sql){

        //1.获取连接
        coon = this.getConnection();
        try {
            //2.得到执行sql的statement的对象
            stmt = coon.createStatement();
            rs = stmt.executeQuery(sql);

        } catch (SQLException throwables) {
            this.closeALL();
            throwables.printStackTrace();
        }
        return rs;
    }


    //增删改 -- executUpdate()
    public int update(String sql){

        int i = 0;
        //1获取连接
         coon = this.getConnection();
        try {
            //2得到执行sql的Statment对象
            stmt = coon.createStatement();
            i = stmt.executeUpdate(sql);
        } catch (SQLException throwables) {
            this.closeALL();
            throwables.printStackTrace();
        }
        return i ;
    }


    //关闭资源
    public void closeALL(){
        if(rs!= null){
            try {
                rs.close();

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(stmt!= null){
            try {
                stmt.close();

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

}